/**
 * ----------------------------------------------------
 * 国际化插件 see https://kazupon.github.io/vue-i18n/zh/
 * ----------------------------------------------------
 */

import type { App } from '@/plugins/types';
import VueI18n from 'vue-i18n';

/*element ui国际化*/
import locale from 'element-ui/lib/locale';

let AllMessages: any;
export const getMessages = () => {
  if (AllMessages) {
    return AllMessages;
  }

  //因为Object.fromEntries是ES10的东西，为了老掉牙的浏览器兼容一下
  if (!Object.fromEntries) {
    Object.defineProperty(Object, 'fromEntries', {
      value(entries: any) {
        if (!entries || !entries[Symbol.iterator]) {
          throw new Error('Object.fromEntries() requires a single iterable argument');
        }
        const o = {};
        Object.keys(entries).forEach(key => {
          const [k, v] = entries[key];
          o[k] = v;
        });
        return o;
      }
    });
  }

  let langMessages = {};
  // 用fromEntries将entries出来的[键值对数组列表]转为[对象]
  AllMessages = Object.fromEntries(
    Object.entries(
      // 支持 json, yml 文件格式，优先使用 yml 文件的语言配置
      import.meta.globEager('../../../langs/**/*.{js,json(5)?,y(a)?ml}')
    ).map(([key, value]) => {
      const filseName = key.replace(/(.*\/)*([^.]+).*/gi, '$2');
      //@ts-ignore
      const result = Object.assign(langMessages[filseName] || {}, value.default);
      //@ts-ignore
      langMessages[filseName] = result;
      return [filseName, result];
    })
  );
  langMessages = {};
  return AllMessages;
};

// 获取浏览器默认语言
export const getBrowserLang = function () {
  //@ts-ignore
  const browserLang = navigator.language ? navigator.language : navigator.browserLanguage;
  let defaultBrowserLang = '';
  if (browserLang.toLowerCase() === 'cn' || browserLang.toLowerCase() === 'zh' || browserLang.toLowerCase() === 'zh-cn') {
    defaultBrowserLang = 'zh-CN';
  } else {
    defaultBrowserLang = 'en';
  }
  return defaultBrowserLang;
};

export default (app: App) => {
  app.use(VueI18n);

  const messages = getMessages();

  /* @__PURE__ */
  import.meta.env.DEBUG && console.log('获取到的语言数据', messages);

  const defaultLocale = localStorage.getItem('app-locale') || getBrowserLang();

  const i18n = new VueI18n({
    formatFallbackMessages: true,
    silentFallbackWarn: true, //是否去除没有翻译给定关键字的 Fall back 警告
    silentTranslationWarn: true, //是否去除国际化无效键值的 Not found 警告
    locale: defaultLocale, // 默认语言
    fallbackLocale: ['en'], //备用语言
    messages
  });

  // 注册全局无刷新切换语言
  app.prototype.setLang = (locale: string) => {
    localStorage.setItem('app-locale', locale);
    i18n.locale = locale;
  };

  //为了实现elementUI插件的多语言切换
  locale.i18n((key: string, value: string) => i18n.t(key, value));

  return { i18n };
};
